<template>
  <div>
    <div>
      <div class="space-between align-center relative" v-if="!props.isDetails">
        <div class="divTip3" >
          <span class="title">输入制单明细</span>
          <i class="arrow"></i>
          <div  class="point-mo"><span>2</span></div>
        </div>
        <div class='blue-line mb-13 mt-10'>制单明细</div>
      </div>
      <a-form ref="baseForm" :model="baseData">
        <a-table rowKey="index" bordered size="small" :dataSource="baseData" :columns="schColumns" :pagination="false" class="form-table mb-20" :scroll="{y: 400}" id="uniqTable">
          <template #headerCell="{ column }">
            <template v-if="column.key === 'colorCode'">
              <span class="text-red">*</span>颜色
            </template>
            <template v-if="column.key === 'sizeCode'">
              <span class="text-red">*</span>尺码
            </template>
            <template v-if="column.key === 'quantity'">
              <span class="text-red">*</span>计划数量
            </template>
            <template v-if="column.key === 'operate'">
              <a-button type="link" class="primary-link" @click="handleAdd(null)">添加</a-button>
            </template>
          </template>
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'poNo'">
              <span v-if="props.isDetails">{{record.poNo}}</span>
              <a-input v-else :placeholder="$t('common.pleaseInput')" :disabled="props.isProd && record.id >=1&& record.isUser" v-model:value.trim="record.poNo" allowClear />
            </template>
            <template v-if="column.key === 'cutterNo'">
              <span v-if="props.isDetails">{{record.cutterNo}}</span>
              <a-input v-else :placeholder="$t('common.pleaseInput')" :disabled="props.isProd && record.id >=1&& record.isUser" v-model:value.trim="record.cutterNo" allowClear />
            </template>
            <template v-if="column.key === 'tailorBill'">
              <span v-if="props.isDetails">{{record.tailorBill}}</span>
              <a-input v-else :placeholder="$t('common.pleaseInput')" :disabled="props.isProd && record.id >=1 && record.isUser" v-model:value.trim="record.tailorBill" allowClear />
            </template>
            <template v-if="column.key === 'colorCode'" >
              <span v-if="props.isDetails">{{record.color}}</span>
              <a-form-item v-else :name="[index, 'colorCode']" :rules="{ required: true, message: '请选择颜色'}">
                <a-select v-model:value="record.colorCode" placeholder="请选择颜色" :disabled="record.isUser" :class="{'single-border': !record.colorCode}" >
                  <a-select-option v-for="item in colorList" :key="item.key" :value="item.code">{{item.nameCodeValue}}</a-select-option>
                </a-select>
              </a-form-item>
            </template>
            <template v-if="column.key === 'sizeCode'">
              <span v-if="props.isDetails">{{record.size}}</span>
              <a-form-item v-else :name="[index, 'sizeCode']" :rules="{ required: true, message: '请选择尺码'}">
                <a-select v-model:value="record.sizeCode" placeholder="请选择尺码" :disabled="record.isUser" :class="{'single-border': !record.sizeCode}">
                  <a-select-option v-for="item in sizeList" :key="item.key" :value="item.code">{{item.nameCodeValue}}</a-select-option>
                </a-select>
              </a-form-item>

            </template>
            <template v-else-if="column.key === 'quantity'">
              <div class="text-right" v-if="props.isDetails">{{record.quantity}}</div>
              <a-form-item v-else :name="[index, 'quantity']" :rules="[{ validator: (_rule, value)=> validateQty(_rule, value, record), trigger: 'change' }]">
                <a-input-number :placeholder="$t('common.pleaseInput')" v-model:value="record.quantity" min="0" allowClear :class="{'single-border': !record.quantity}" />
              </a-form-item>
            </template>
            <template v-else-if="column.key === 'operate'">
              <span class="table-operate-container">
                <a-button type="link" class="primary-link" @click="handleAdd(record)">新增</a-button>
                <a-divider type="vertical" />
                <a-button type="link" class="warning-link" :disabled="baseData.length === 1 || record.isUser" @click="handleDelete(record.id)">删除</a-button>
              </span>
            </template>
          </template>
          <template #summary v-if="baseData.length">
            <a-table-summary fixed>
              <a-table-summary-row class="text-center">
                <a-table-summary-cell>合计</a-table-summary-cell>
                <a-table-summary-cell v-for="el in columnsAry" :key="el" class="text-center">
                  <span v-if="el == 6">{{getColumnTotal('produceQty')}}</span>
                  <span v-else-if="el == 7">{{getColumnTotal('inputQty')}}</span>
                  <span v-else-if="el == 8">{{getColumnTotal('finishedQty')}}</span>
                  <span v-else-if="el == 9">{{getColumnTotal('unfinishedQty')}}</span>
                </a-table-summary-cell>


                <a-table-summary-cell :index="9" v-if="!props.isDetails"></a-table-summary-cell>
              </a-table-summary-row>
            </a-table-summary>
          </template>
        </a-table>
      </a-form>
    </div>
  </div>
</template>
<script setup name="makeDetailTable">
import { cloneDeep } from 'lodash'
import { ref, watch, nextTick, onMounted } from 'vue'
import { schColumns } from './makeConfig'
const props = defineProps({
  tableData: { type: Array, default: () => [] },
  isDetails: { type: Boolean, default: () => false },
  isProd: { type: Boolean, default: () => false }
})
let columnsAry = Array.from(Array(10), (v, k) => k)
let colorList = ref([])
let sizeList = ref([])
let baseData = ref([])
let baseForm = ref()

const getColumnTotal = (column) => {
  return baseData.value.reduce((prev, next) => {
    return next[column] ? prev + next[column] : prev
  }, 0)
}
const handleAdd = async (record) => {
  let obj = { colorCode: undefined, sizeCode: undefined, id: Math.random(), quantity: 0 }
  if (record) {
    obj.colorCode = record.colorCode
    obj.sizeCode = record.sizeCode
  }
  baseData.value.push(obj)
  await nextTick()
  scrollBottom()
}
const scrollBottom = () => {
  const tables = document.querySelectorAll('#uniqTable .ant-table-body')[0]
  let scrollHeight = tables.scrollHeight
  let clientHeight = tables.clientHeight
  if (scrollHeight > clientHeight) tables.scrollTop = scrollHeight + 100
}
const handleDelete = (id) => {
  const dataList = baseData.value.filter(item => item.id !== id)
  baseData.value = dataList
}

const initBaseData = (newVal) => {
  const tableData = cloneDeep(newVal)
  console.log("🚀 ~ file: makeDetailTable.vue:118 ~ initBaseData ~ tableData:", tableData)
  baseData.value = tableData
}

const onConfigAdd = (color, size) => {
  colorList.value = color
  sizeList.value = size
  baseData.value.forEach(i => {
    i.colorCode = color.map(el => el.code).includes(i.colorCode) ? i.colorCode : undefined
    i.sizeCode = size.map(el => el.code).includes(i.sizeCode) ? i.sizeCode : undefined
  })
}
const validateQty = async (_rule, value, record) => {
  if (!value) {
    return Promise.reject('请输入计划数量')
  } else {
    if (/(^[1-9]([0-9]+)?$)/.test(value)) {
      if (record.isUser && value < record.scheduleQuantity) {
        return Promise.reject('编辑数量必须大于等于已分配数量')
      } else {
        return Promise.resolve()
      }
    } else {
      return Promise.reject('只能输入整数')
    }
  }
}
watch(() => props.tableData, (newVal) => {
  initBaseData(newVal)
}, { deep: true, immediate: true })
defineExpose({
  baseForm,
  onConfigAdd,
  baseData
})
onMounted(() => {

})
</script>
